package com.zr.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zr.model.User;
import com.zr.service.JlcxServiceljc;
import com.zr.service.LoginServicecy;
import com.zr.serviceImpl.JlcxServiceImplljc;
import com.zr.serviceImpl.LoginServiceImplcy;

public class LoginControllercy extends HttpServlet{
	//创建用户对象
	LoginServicecy  us = new LoginServiceImplcy();
	JlcxServiceljc j = new JlcxServiceImplljc();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	doPost(req, resp);
}
@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	//创建session对象
	HttpSession session =req.getSession();
	//创建返回值对象
 	PrintWriter pr=resp.getWriter();
 	
 	//清理session的值 防止用户未关闭浏览器直接重新登陆
    Enumeration attributeNames = session.getAttributeNames();  
    while(attributeNames.hasMoreElements()){  
        String attrName = attributeNames.nextElement().toString();  
        session.setAttribute(attrName, null);  
        session.removeAttribute(attrName);  
    }   
    //从页面获取用户名与密码值 
 	String uname=req.getParameter("uname");
 	String upsw=req.getParameter("upsw");
 	String ck=req.getParameter("ck");
 	if("y".equals(ck)){
		 Cookie nameCookie = new Cookie("username", uname);
		 nameCookie.setMaxAge(60 * 60 * 24 * 3);
		 Cookie pswCookie = new Cookie("password", upsw);
		 pswCookie.setMaxAge(60 * 60 * 24 * 3);
		  resp.addCookie(nameCookie);
		  resp.addCookie(pswCookie);
	}
 	
 	User i =us.LoginUser(uname, upsw);
 	//判断是否用户是否存在
 	if(i.getUid()>0){
 		//在session中保存该用户的信息
 		if(i.getRid()==1){
 			int count = j.countAllJL();
 			session.setAttribute("msg", "你有");
 			session.setAttribute("count", count);
 			session.setAttribute("msg1", "条成绩修改请求需审批，请及时处理");
 		}
 		if(i.getRid()==2){
 			int tid = i.getTid();
 			String tname = j.findTnameByTid(tid);
 			int count = j.countAllJLBytname(tname);
 			session.setAttribute("msg", "你有");
 			session.setAttribute("count", count);
 			session.setAttribute("msg1", "条成绩修改请求已被处理，请注意查看");
 		}
 		session.setAttribute("User",i);
 		pr.write("1");
 	}else{
 		pr.write("0");
 	}
 	
	}
}
